package com.tju.welding.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.tju.welding.dao.ProjectMapper;
import com.tju.welding.dao.UserMapper;
import com.tju.welding.pojo.Project;
import com.tju.welding.pojo.ProjectMember;
import com.tju.welding.pojo.User;
import com.tju.welding.service.ProjectService;
import com.tju.welding.utils.ApiResponse;
import com.tju.welding.utils.Code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public ApiResponse createProject(String projectName, HttpSession session) {
        try {
            User presentUser = (User) session.getAttribute("user");
            Project temp = projectMapper.getProjectByProjectName(projectName);
            //工程名称检查无冲突
            if (temp == null) {
                projectMapper.addProject(projectName, presentUser.getUserId());
                // 获取刚刚新建的工程的id
                int projectId = projectMapper.getProjectIdByProjectName(projectName);
                // 工程的创建者自动成为工程的管理员
                projectMapper.addProjectMember(projectId, presentUser.getUserId(), 1);
                return ApiResponse.success("ok");
            } else {
                return ApiResponse.error(Code.NAME_EXISTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

    /**
     * 将成员添加至工程
     * 返回1，添加成功
     * 返回2，用户不存在
     * 返回3，工程不存在
     * 返回0，其他错误
     */
    private int addMemberToProject(int projectId, int memberId, int memberType) {
        try {
            Project tempProject = projectMapper.getProjectByProjectId(projectId);
            if (tempProject == null)
                return 3;
            User tempUser = userMapper.getUserByUserId(memberId);
            if (tempUser == null)
                return 2;
            projectMapper.addProjectMember(projectId, memberId, memberType);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public ApiResponse addProjectMember(int projectId, int userId, int memberType, HttpSession session) {
        try {
            // 验证待添加的用户和工程的存在性
            Project tempProject = projectMapper.getProjectByProjectId(projectId);
            if (tempProject == null)
                return ApiResponse.error(Code.PROJECT_NOT_FOUND);
            User tempUser = userMapper.getUserByUserId(userId);
            if (tempUser == null)
                return ApiResponse.error(Code.USER_NOT_FOUND);

            // 检查当前用户是否有添加工程成员的权限
            User presentUser = (User) session.getAttribute("user");
            ProjectMember presentProjectMember = projectMapper
                    .getProjectMemberByMemberIdAndProjectId(presentUser.getUserId(), projectId);
            if (presentProjectMember == null)
                return ApiResponse.error(Code.UNAUTHORIZED);
            else if (presentProjectMember.getMemberType() != 1)
                return ApiResponse.error(Code.UNAUTHORIZED);
            else {
                addMemberToProject(projectId, userId, memberType);
                return ApiResponse.success("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

    @Override
    public ApiResponse alterProjectName(int projectId, String newName, HttpSession session) {
        try {
            // 验证待修改名称的工程的存在性
            Project tempProject = projectMapper.getProjectByProjectId(projectId);
            if (tempProject == null)
                return ApiResponse.error(Code.PROJECT_NOT_FOUND);
            // 检查当前用户是否有修改工程名称的权限
            User presentUser = (User) session.getAttribute("user");
            ProjectMember presentProjectMember = projectMapper
                    .getProjectMemberByMemberIdAndProjectId(presentUser.getUserId(), projectId);
            if (presentProjectMember == null)
                return ApiResponse.error(Code.UNAUTHORIZED);
            else if (presentProjectMember.getMemberType() != 1)
                return ApiResponse.error(Code.UNAUTHORIZED);
            else {
                projectMapper.alterProjectName(projectId, newName);
                return ApiResponse.success("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

    @Override
    public ApiResponse deleteProjectMember(int projectId, int userId, HttpSession session) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiResponse assignJob(int portId, int userId, HttpSession session) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiResponse getManagedProject(HttpSession session) {
        try {
            User presentUser = (User) session.getAttribute("user");
            // 获取用户加入的所有工程
            List<ProjectMember> joinedProjectList = projectMapper.getProjectMemberByMemberId(presentUser.getUserId());
            // 预备存放用户管理的所有工程
            List<Project> managedProjectList = new ArrayList<>();
            // 在用户加入的工程中筛选出用户管理的工程
            for (ProjectMember temp : joinedProjectList) {
                if (temp.getMemberType() == 1 && temp.getIsDeleted() == 0) {
                    managedProjectList.add(projectMapper.getProjectByProjectId(temp.getProjectId()));
                }
            }
            return ApiResponse.success(managedProjectList);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

}
